﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using CafeOnline.MvcFramework.Composition;
using CafeOnline.MvcFramework.Interfaces;

namespace CafeOnline.MvcFramework.Grid {
    [Export]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class GridProvider {
#pragma warning disable 0649,0169
        [ImportMany(AllowRecomposition = true)]
        private IEnumerable<Lazy<IGridFactory, IGridFactoryMetadata>> m_gridFactories;
        [ImportMany(AllowRecomposition = true)]
        private IEnumerable<Lazy<IColumnFactory, IColumnFactoryMetadata>> m_gridColumns;
#pragma warning restore 0649,0169
        public IGridFactory GetGridFactory(string gridTypeName) {
            var res = m_gridFactories.FirstOrDefault(x => x.Metadata.GridTypeName.Equals(gridTypeName));
            if (res != null) {
                return res.Value;
            }
            return null;
        }

        public IEnumerable<Lazy<IColumnFactory, IColumnFactoryMetadata>> GetColumns(string gridType) {
            

            var res = m_gridColumns.Where(c => Regex.IsMatch(gridType, c.Metadata.GridType,
                                        RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase))
                                    .OrderBy(t => t.Metadata.Order);
            var columns = new Dictionary<string, Lazy<IColumnFactory, IColumnFactoryMetadata>>();
            foreach (var item in res) {
                string columnName = item.Metadata.ColumnName;
                if (columns.ContainsKey(columnName)) {
                    Lazy<IColumnFactory, IColumnFactoryMetadata> current = columns[columnName];
                    if (current.Metadata.Priority > item.Metadata.Priority) {
                        columns[columnName] = item;
                    }
                } else {
                    columns.Add(columnName, item);
                }
            }
            return columns.Where(t => !t.Value.Metadata.Excluded).Select(t => t.Value);

        }
    }
}
